package com.geline.mybatisplus.interceptor;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * mybatis后置拦截器：用于回调更新主表信息
 *
 * @author mx
 * @date 2025/8/25
 */
@Intercepts({@Signature(
        type = Executor.class,
        method = "update",
        args = {MappedStatement.class, Object.class}
)})
public class MybatisInnerAfterInterceptor implements Interceptor {

    private List<InnerAfterInterceptor> interceptors = new ArrayList();

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object target = invocation.getTarget();
        Object[] args = invocation.getArgs();
        Object proceed = null;
        if (target instanceof Executor) {
            Executor executor = (Executor)target;
            Object parameter = args[1];
            boolean isUpdate = args.length == 2;
            MappedStatement ms = (MappedStatement)args[0];

            if (isUpdate) {
                for(InnerAfterInterceptor update : this.interceptors) {
                    if (!update.willDoUpdate(executor, ms, parameter)) {
                        return -1;
                    }
                }
            }

            //正常执行SQL
            proceed = invocation.proceed();

            if (isUpdate) {
                for(InnerAfterInterceptor update : this.interceptors) {
                    if (!update.afterUpdate(executor, ms, parameter)) {
                        return -1;
                    }
                }
            }
        }
        return proceed;
    }

    public Object plugin(Object target) {
        return !(target instanceof Executor) && !(target instanceof StatementHandler) ? target : Plugin.wrap(target, this);
    }

    public void addInnerInterceptor(InnerAfterInterceptor innerInterceptor) {
        this.interceptors.add(innerInterceptor);
    }

    public List<InnerAfterInterceptor> getInterceptors() {
        return Collections.unmodifiableList(this.interceptors);
    }

    public void setInterceptors(final List<InnerAfterInterceptor> interceptors) {
        this.interceptors = interceptors;
    }

}
